package com.ruoyi.eqmonitor.dispose.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.eqmonitor.dispose.domain.ExteriorSiteMonitorData;
import com.ruoyi.eqmonitor.dispose.dtos.*;
import com.ruoyi.eqmonitor.dispose.mapper.ExteriorSiteMonitorDataServiceMapper;
import com.ruoyi.eqmonitor.dispose.service.ExteriorSiteMonitorDataService;
import com.ruoyi.eqmonitor.dtos.WordReportDto;
import com.ruoyi.eqmonitor.smdtv.domain.Smdtv9;
import com.ruoyi.eqmonitor.smdtv.service.ISmdtv9Service;
import com.ruoyi.eqmonitor.utils.Constant;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 外部接口-微站站点实时数据服务实现
 */
@Service
public class ExteriorSiteMonitorDataServiceImpl extends ServiceImpl<ExteriorSiteMonitorDataServiceMapper, ExteriorSiteMonitorData> implements ExteriorSiteMonitorDataService {


    @Resource
    private ExteriorSiteMonitorDataServiceMapper siteMonitorDataServiceMapper;
    @Resource
    private ISmdtv9Service ISmdtv9Service;

    @Override
    public List<ExteriorSiteMonitorData> getInfo(SiteMonitorDataDto siteMonitorDataDto) {
//        String dataTimeString = siteMonitorDataDto.getDataTime();
//        Date dataTime = DateUtils.dateTime("yyyy-MM-dd",dataTimeString);
        Date dataTime = siteMonitorDataDto.getDataTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dataTime);
        int year = calendar.get(Calendar.YEAR);//年
        int month = calendar.get(Calendar.MONTH)+1;//月
        int day = calendar.get(Calendar.DAY_OF_MONTH);//日
        int week = calendar.get(Calendar.WEEK_OF_YEAR);//一年中的第几周
        return siteMonitorDataServiceMapper.getInfo(siteMonitorDataDto.getSiteName(),
                year,month,day,week,siteMonitorDataDto.getTimeCode());
    }

    @Override
    public List<ExteriorSiteMonitorData> lastData(String siteCode) {
        return baseMapper.lastData(siteCode);
    }

    @Override
    public List<ExteriorSiteMonitorData> lastListData(String siteName) {
        return siteMonitorDataServiceMapper.lastListData(siteName);
    }

    @Override
    public Map<String, List<SiteMonitorDataGetAllDto>> getAll() {
        List<SiteMonitorDataGetAllDto> all = baseMapper.getAll(null,null,null,null);

        //根据微站名称分组
        Map<String, List<SiteMonitorDataGetAllDto>> collect = null;
        if (all.size() != 0){
            collect = all.stream().collect(Collectors.groupingBy(SiteMonitorDataGetAllDto::getSiteName));
        }
        return collect;
    }

    @Override
    public List<SiteMonitorDataGetAllDto> getWaterQuality(SiteMonitorDataDto dto) {
        return baseMapper.getWaterQuality(dto);
    }

    @Override
    public List<SiteMonitorDataGetAllDto> getWaterQualityBackstageExport(SiteMonitorDataDto dto) {
        List<SiteMonitorDataGetAllDto> dtos = new ArrayList<>();
        List<SiteMonitorDataGetAllDto> quality = baseMapper.getWaterQuality(dto);
        //根据站点名称分组
        Map<String, List<SiteMonitorDataGetAllDto>> listMap = quality.stream().collect(Collectors.groupingBy(SiteMonitorDataGetAllDto::getSiteName));
        for (String siteName : listMap.keySet()){
            //根据类别分组
            List<SiteMonitorDataGetAllDto> list = listMap.get(siteName);
            Map<String, List<SiteMonitorDataGetAllDto>> listMap1 = list.stream().collect(Collectors.groupingBy(SiteMonitorDataGetAllDto::getParamName));
            for (String paramName : listMap1.keySet()){
                List<SiteMonitorDataGetAllDto> list1 = listMap1.get(paramName);

                String dataTimeFlag = null;//标记时间
                String jzmFlag = null;//水质目标标记
                Double sumValue = 0.000;//累计数值
                String x = null;//横坐标
                String y = null;//纵坐标
                int i = 0;//累计数值的个数
                for (SiteMonitorDataGetAllDto en : list1){
                    String dataTime = en.getDataTime().substring(0,10);
                    Double v = Double.parseDouble(en.getDataValue());
                    //首次循环
                    if (dataTimeFlag == null){
                        dataTimeFlag = dataTime;
                        jzmFlag = en.getJzm();
                        x = en.getX();
                        y = en.getY();
                        sumValue = v;
                        i = 1;
                    }
                    //同一天
                    if (dataTimeFlag.equals(dataTime)){
                        sumValue += v;
                        i++;
                    }else {
                        SiteMonitorDataGetAllDto allDto = new SiteMonitorDataGetAllDto();
                        allDto.setSiteName(siteName);//站点名称
                        allDto.setParamName(paramName);//类别
                        BigDecimal divide = new BigDecimal(sumValue).divide(new BigDecimal(i), 3, BigDecimal.ROUND_HALF_UP);
                        allDto.setAvgValue(divide.toString());//日均值
                        allDto.setDataTime(dataTimeFlag);//时间
                        allDto.setJzm(jzmFlag);//水质目标
                        //allDto.setOverproof(this.ifOverproof(paramName,jzmFlag,divide));//超标因子
                        allDto.setX(x);
                        allDto.setY(y);
                        dtos.add(allDto);
                        //重置
                        dataTimeFlag = dataTime;
                        jzmFlag = en.getJzm();
                        x = en.getX();
                        y = en.getY();
                        sumValue = v;
                        i = 1;
                    }
                }
                //最后一轮的数据
                SiteMonitorDataGetAllDto allDto = new SiteMonitorDataGetAllDto();
                allDto.setSiteName(siteName);//站点名称
                allDto.setParamName(paramName);//类别
                BigDecimal divide = new BigDecimal(sumValue).divide(new BigDecimal(i), 3, BigDecimal.ROUND_HALF_UP);
                allDto.setAvgValue(divide.toString());//日均值
                allDto.setDataTime(dataTimeFlag);//时间
                allDto.setJzm(jzmFlag);//水质目标
                //allDto.setOverproof(this.ifOverproof(paramName,jzmFlag,divide));//超标因子
                dtos.add(allDto);
            }
        }
        return dtos;
    }

    @Override
    public List<SiteMonitorDataGetAllVo> getWaterQualityBackstage(String name) {
        List<String> nameList = new ArrayList<>();
        if (name != null){
            nameList.add(name);
        }
        List<SiteMonitorDataGetAllDto> all = baseMapper.getAll(nameList,null,null,null);

        //判断是否超标及现状
        for (SiteMonitorDataGetAllDto dto : all){
            SiteMonitorDataGetAllDto value = Constant.WaterStandard.getValue(dto.getParamName(), dto.getJzm(), dto.getDataValue());
            dto.setNowJzm(value.getNowJzm());//加入现状
            dto.setIfOverproof(value.getIfOverproof());//是否超标
            dto.setCode(value.getCode());//现状编码
        }
        List<SiteMonitorDataGetAllVo> vos = new ArrayList<>();
        //根据微站名称分组
        Map<String, List<SiteMonitorDataGetAllDto>> collect = null;
        if (all.size() != 0){
            collect = all.stream().collect(Collectors.groupingBy(SiteMonitorDataGetAllDto::getSiteName));
            for (String key : collect.keySet()){
                SiteMonitorDataGetAllVo vo = new SiteMonitorDataGetAllVo();
                vo.setSiteName(key);
                List<SiteMonitorDataGetAllDto> list = collect.get(key);
                vo.setList(list);
                Integer codeFlag = 0;//现状编码标记
                String jzmZ = null;//目标标记
                String nowJzmFlag = null;//现状标记
                StringBuilder strings = new StringBuilder();//超标因子
                //1.判断是否超标 2.加入超标因子 3.加入微站现状
                for (SiteMonitorDataGetAllDto d : list){
                    //判断是否超标
                    if (d.getIfOverproof()){
                        vo.setIfOverproofA(true);
                        String paramName = d.getParamName();
                        String dataValue = d.getDataValue();
                        strings.append(paramName).append("(").append(dataValue).append("),");
                    }
                    Integer code = d.getCode();
                    //判断最高级现状
                    if (code > codeFlag){
                        codeFlag = code;
                        jzmZ = d.getJzm();
                        nowJzmFlag = d.getNowJzm();
                    }
                }
                vo.setJzmZ(jzmZ);
                vo.setNowJzmZ(nowJzmFlag);//加入现状
                //加入超标因子
                if (strings.length()>1){
                    strings.deleteCharAt(strings.length()-1);
                }
                if (vo.getIfOverproofA() == null){
                    vo.setIfOverproofA(false);
                }
                vo.setOverproof(strings.toString());
                vos.add(vo);
            }
        }
        return vos;
    }

    @Override
    public List<JudgeOverproofVo> judgeOverproof(String areaName, String beginTime, String endTime){
        List<Smdtv9> byAreaName = ISmdtv9Service.getByAreaName(areaName);
        ArrayList<String> siteNameList = new ArrayList<>();
        if (byAreaName.size() > 0){
            for (Smdtv9 smdtv9 : byAreaName){
                siteNameList.add(smdtv9.getName());
            }
        }
        WaterQualityMergeDto dto = new WaterQualityMergeDto();
        dto.setAreaName(areaName);
        dto.setSiteName(siteNameList);
        dto.setBeginTime(beginTime);
        dto.setEndTime(endTime);
        //查询数据
        List<WaterQualityMergeVO> waterQualityMerge = this.getWaterQualityMerge(dto);
        List<JudgeOverproofVo> vos = new ArrayList<>();
        //根据街道名称分组
        Map<String, List<WaterQualityMergeVO>> collect = waterQualityMerge.stream().collect(Collectors.groupingBy(WaterQualityMergeVO::getAreaName));
        for (String key : collect.keySet()){
            JudgeOverproofVo judgeOverproofVo = new JudgeOverproofVo();
            judgeOverproofVo.setAreaName(key);
            List<WaterQualityMergeVO> mergeVOS = collect.get(key);
            //统计达标数
            Long sum = 0L;
            for (WaterQualityMergeVO vo : mergeVOS){
                if (!vo.getIfOverproofA()){
                    sum++;
                }
            }
            judgeOverproofVo.setSum(sum);
            vos.add(judgeOverproofVo);
        }
        return vos;
    }

    @Override
    public List<StatementExportVo> getStatementExport(SiteMonitorDataDto dto) throws ParseException {
        //处理参数
        Calendar c = Calendar.getInstance();
        String beginTime = dto.getBeginTime();
        int timeCode = dto.getTimeCode();
        SimpleDateFormat sdf = null;
        if (timeCode == 1){
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(beginTime);
            c.setTime(parse);
            c.add(Calendar.DAY_OF_MONTH,1);
            beginTime = sdf.format(parse);
        } else if (timeCode == 2){
            beginTime = beginTime + "-01";
            sdf = new SimpleDateFormat("yyyy-MM-01");
            Date parse = sdf.parse(beginTime);
            c.setTime(parse);
            c.add(Calendar.MONTH,1);
        }else if (timeCode == 4){
            beginTime = beginTime + "-01-01";
            sdf = new SimpleDateFormat("yyyy-01-01");
            Date parse = sdf.parse(beginTime);
            c.setTime(parse);
            c.add(Calendar.YEAR,1);
        }
        dto.setBeginTime(beginTime);
        dto.setEndTime(sdf.format(c.getTime()));
        //查询数据
        List<StatementVo> vos = baseMapper.getStatement(dto);
        //处理数据
        List<StatementExportVo> statementExportVos = new ArrayList<>();
        Map<String, List<StatementVo>> collect = vos.stream().collect(Collectors.groupingBy(StatementVo::getSiteName));
        for (String key : collect.keySet()){
            StatementExportVo statementExportVo = new StatementExportVo();
            statementExportVo.setSiteName(key);//设置站点名称
            List<StatementVo> list = collect.get(key);
            if (timeCode == 2){   //月报表
                SimpleDateFormat sdfY = new SimpleDateFormat("yyyy-MM-dd");
                list = this.disposeData(sdfY, list);
            }else if (timeCode == 4){   //年报表
                SimpleDateFormat sdfN = new SimpleDateFormat("yyyy-MM");
                list = this.disposeData(sdfN, list);
            }
//            else if (timeCode == 3){
//
//            }
            statementExportVo.setList(list);

            BigDecimal adTotal = BigDecimal.ZERO;
            BigDecimal zlTotal = BigDecimal.ZERO;
            BigDecimal gmsyTotal = BigDecimal.ZERO;
            BigDecimal adMaxValue = BigDecimal.ZERO, adMinValue = BigDecimal.ZERO;
            BigDecimal zlMaxValue = BigDecimal.ZERO, zlMinValue = BigDecimal.ZERO;
            BigDecimal gmsyMaxValue = BigDecimal.ZERO, gmsyMinValue = BigDecimal.ZERO;
            for (StatementVo vo : list){
                BigDecimal adValue = vo.getAdValue().equals("--") ? BigDecimal.ZERO : new BigDecimal(vo.getAdValue());
                BigDecimal zlValue = vo.getZlValue().equals("--") ? BigDecimal.ZERO : new BigDecimal(vo.getZlValue());
                BigDecimal gmsyValue = vo.getGmsyValue().equals("--") ? BigDecimal.ZERO : new BigDecimal(vo.getGmsyValue());

                //判断最大值
                if (adValue.compareTo(adMaxValue) > 0){
                    adMaxValue = adValue;
                }
                if (zlValue.compareTo(zlMaxValue) > 0){
                    zlMaxValue = zlValue;
                }
                if (gmsyValue.compareTo(gmsyMaxValue) > 0){
                    gmsyMaxValue = gmsyValue;
                }
                //判断最小值
                if (adValue.compareTo(adMinValue) < 0){
                    adMinValue = adValue;
                }
                if (zlValue.compareTo(zlMinValue) < 0){
                    zlMinValue = zlValue;
                }
                if (gmsyValue.compareTo(gmsyMinValue) < 0){
                    gmsyMinValue = gmsyValue;
                }

                adTotal = adTotal.add(adValue);
                zlTotal = zlTotal.add(zlValue);
                gmsyTotal = gmsyTotal.add(gmsyValue);
            }
            //设置最大值、最小值和平均值
            statementExportVo.setAdMaxValue(adMaxValue.toString());
            statementExportVo.setAdMinValue(adMinValue.toString());
            statementExportVo.setZlMaxValue(zlMaxValue.toString());
            statementExportVo.setZlMinValue(zlMinValue.toString());
            statementExportVo.setGmsyMaxValue(gmsyMaxValue.toString());
            statementExportVo.setGmsyMinValue(gmsyMinValue.toString());
            int size = list.size();
            if (size > 0){
                statementExportVo.setAdAvgValue(adTotal.divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP).toString());
                statementExportVo.setZlAvgValue(zlTotal.divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP).toString());
                statementExportVo.setGmsyAvgValue(gmsyTotal.divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP).toString());
            }
            statementExportVos.add(statementExportVo);
        }
        return statementExportVos;
    }

    @Override
    public Map<String,List<SiteMonitorDataGetAllDto>> getHistory(String siteName,Integer state) {
        List<String> nameList = new ArrayList<>();
        if (siteName != null){
            nameList.add(siteName);
        }
        List<SiteMonitorDataGetAllDto> history = null;
        if (state == 0){
            history = baseMapper.getAll(nameList, null, null, null);
        }else if (state == 1){
            history = baseMapper.getHistory(siteName, state,null);
        }else {
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.MONTH, -1);
            Date time = c.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(time);
            history = baseMapper.getHistory(siteName, state,format);
        }
        return history.stream().collect(Collectors.groupingBy(SiteMonitorDataGetAllDto::getParamName));
    }

    @Override
    public List<WaterQualityMergeVO> getWaterQualityMerge(WaterQualityMergeDto dto) {
        List<WaterQualityMergeDetailsVO> waterQualityMerge = new ArrayList<>();
        String beginTime = dto.getBeginTime();
        String endTime = dto.getEndTime();
        //最近数据
        if (beginTime == null){
            List<SiteMonitorDataGetAllDto> all = baseMapper.getAll(dto.getSiteName(),dto.getAreaName(),null,null);
            for (SiteMonitorDataGetAllDto siteMonitorDataGetAllDto : all){
                WaterQualityMergeDetailsVO vo = new WaterQualityMergeDetailsVO();
                vo.setId(siteMonitorDataGetAllDto.getId());
                vo.setAreaName(siteMonitorDataGetAllDto.getAreaName());
                vo.setSiteName(siteMonitorDataGetAllDto.getSiteName());
                vo.setDataTime(siteMonitorDataGetAllDto.getDataTime());
                vo.setDataValue(siteMonitorDataGetAllDto.getDataValue());
                vo.setParamName(siteMonitorDataGetAllDto.getParamName());
                vo.setJzm(siteMonitorDataGetAllDto.getJzm());
                vo.setX(siteMonitorDataGetAllDto.getX());
                vo.setY(siteMonitorDataGetAllDto.getY());
                waterQualityMerge.add(vo);
            }
        }else {
            waterQualityMerge = baseMapper.getWaterQualityMerge(dto.getSiteName(), dto.getAreaName(),beginTime, endTime,0);
        }
        //处理数据
        List<WaterQualityMergeVO> list = new ArrayList<>();
        //根据站点名称分组
        Map<String, List<WaterQualityMergeDetailsVO>> siteNameCollect = waterQualityMerge.stream().collect(Collectors.groupingBy(WaterQualityMergeDetailsVO::getSiteName));
        for (String siteNameKey : siteNameCollect.keySet()){
            WaterQualityMergeExportVo exportVo = new WaterQualityMergeExportVo();
            exportVo.setSiteName(siteNameKey);
            List<WaterQualityMergeDetailsVO> siteNameVOs = siteNameCollect.get(siteNameKey);

            //返回数据
            WaterQualityMergeVO waterQualityMergeVO = new WaterQualityMergeVO();
            waterQualityMergeVO.setAreaName(siteNameVOs.get(0).getAreaName());
            waterQualityMergeVO.setId(siteNameVOs.get(0).getId());//站点id
            waterQualityMergeVO.setSiteName(siteNameKey);   //站点名称
            waterQualityMergeVO.setJzmZ(siteNameVOs.get(0).getJzm());   //站点目标
            waterQualityMergeVO.setX(siteNameVOs.get(0).getX());
            waterQualityMergeVO.setY(siteNameVOs.get(0).getY());

            String nowJzmFlag = null;//现状标记
            Integer codeFlag = 0;//现状编码标记
            StringBuilder overproof = new StringBuilder();//超标因子

            //根据类别分组
            Map<String, List<WaterQualityMergeDetailsVO>> paramNameCollect = siteNameVOs.stream().collect(Collectors.groupingBy(WaterQualityMergeDetailsVO::getParamName));
            for (String paramNameKey : paramNameCollect.keySet()) {
                List<WaterQualityMergeDetailsVO> paramNameVOS = paramNameCollect.get(paramNameKey);

                //计算数值
                BigDecimal sum = new BigDecimal(0);
                int i = 0;
                for (WaterQualityMergeDetailsVO vo : paramNameVOS) {
                    sum = sum.add(new BigDecimal(vo.getDataValue()));
                    i++;
                }
                //防止分母为0异常
                if (i == 0) {
                    i = 1;
                }
                //平均值
                String dataValueString = sum.divide(new BigDecimal(i), 3, BigDecimal.ROUND_HALF_UP).toString();
                switch (paramNameKey){
                    case "氨氮":
                        waterQualityMergeVO.setAdValue(dataValueString);
                        break;
                    case "总磷":
                        waterQualityMergeVO.setZlValue(dataValueString);
                        break;
                    case "高锰酸盐指数":
                        waterQualityMergeVO.setGmsyValue(dataValueString);
                        break;
                }
                //判断单个数据是否超标
                SiteMonitorDataGetAllDto value = Constant.WaterStandard.getValue(paramNameKey, paramNameVOS.get(0).getJzm(), dataValueString);
                Integer code = value.getCode();//类别现状编码
                //判断站点现状(最高类别现状)
                if (code > codeFlag) {
                    codeFlag = code;
                    nowJzmFlag = value.getNowJzm();//类别现状
                }
                //判断站点是否超标(全部类别达标则达标，否则超标)
                Boolean ifOverproof = value.getIfOverproof();
                if (ifOverproof) {
                    waterQualityMergeVO.setIfOverproofA(true); //站点是否超标
                    overproof.append(paramNameKey).append("(").append(dataValueString).append("),");
                }
            }

            waterQualityMergeVO.setNowJzmZ(nowJzmFlag);//站点现状
            //加入超标因子和数值
            if (overproof.length() > 1) {
                overproof.deleteCharAt(overproof.length() - 1);
            }

            if (waterQualityMergeVO.getIfOverproofA() == null) {
                waterQualityMergeVO.setIfOverproofA(false);
            }
            waterQualityMergeVO.setOverproof(overproof.toString());

            list.add(waterQualityMergeVO);
        }
        return list;
    }

    @Override
    public List<WaterQualityMergeVO> getWaterQualityMergeG(WaterQualityMergeDto dto){
        List<WaterQualityMergeDetailsVO> waterQualityMerge = new ArrayList<>();
        //最近的数据
        Integer state = dto.getState();
        if (state == null){
            List<SiteMonitorDataGetAllDto> all = baseMapper.getAll(dto.getSiteName(),dto.getAreaName(),null,null);
            for (SiteMonitorDataGetAllDto siteMonitorDataGetAllDto : all){
                WaterQualityMergeDetailsVO vo = new WaterQualityMergeDetailsVO();
                vo.setId(siteMonitorDataGetAllDto.getId());
                vo.setAreaName(siteMonitorDataGetAllDto.getAreaName());
                vo.setSiteName(siteMonitorDataGetAllDto.getSiteName());
                vo.setDataTime(siteMonitorDataGetAllDto.getDataTime());
                vo.setDataValue(siteMonitorDataGetAllDto.getDataValue());
                vo.setParamName(siteMonitorDataGetAllDto.getParamName());
                vo.setJzm(siteMonitorDataGetAllDto.getJzm());
                vo.setX(siteMonitorDataGetAllDto.getX());
                vo.setY(siteMonitorDataGetAllDto.getY());
                waterQualityMerge.add(vo);
            }
        }else if (state == 6){
            //最新数据（仅断面（微站）报警定时任务使用）
            waterQualityMerge = baseMapper.getWaterQualityMerge(null, null,dto.getBeginTime(), dto.getEndTime(),0);
        }else {
            //处理时间
            String beginTime0 = dto.getBeginTime();
            String endTime0 = dto.getEndTime();
            int beginYear = dto.getBeginYear();
            int endYear = dto.getEndYear();
            int beginDate = dto.getBeginDate();
            int endDate = dto.getEndDate();
            Date beginTime = DateUtils.toDate(state, beginTime0,beginYear, beginDate,false);
            Date endTime = DateUtils.toDate(state, endTime0,endYear, endDate,true);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            waterQualityMerge = baseMapper.getWaterQualityMerge(dto.getSiteName(), dto.getAreaName(),sdf.format(beginTime), sdf.format(endTime),0);
        }

        //处理查询结果的时间字段
        SimpleDateFormat sdf = null;
        if (state == null){
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else if (state == 0){
            sdf = new SimpleDateFormat("yyyy");
        }else if (state == 2 || state == 3){
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }else {
            sdf = new SimpleDateFormat("yyyy-MM");
        }
        for (WaterQualityMergeDetailsVO vo : waterQualityMerge){
            try {
                Date parse = sdf.parse(vo.getDataTime());
                vo.setDataTime(sdf.format(parse));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //处理数据
        List<WaterQualityMergeVO> list = new ArrayList<>();
        //根据站点名称分组
        Map<String, List<WaterQualityMergeDetailsVO>> siteNameCollect = waterQualityMerge.stream().collect(Collectors.groupingBy(WaterQualityMergeDetailsVO::getSiteName));
        for (String siteNameKey : siteNameCollect.keySet()){
            List<WaterQualityMergeDetailsVO> siteNameVOs = siteNameCollect.get(siteNameKey);

            //根据时间分组
            Map<String, List<WaterQualityMergeDetailsVO>> timeCollect = siteNameVOs.stream().collect(Collectors.groupingBy(WaterQualityMergeDetailsVO::getDataTime));
            for (String timeKey : timeCollect.keySet()){
                List<WaterQualityMergeDetailsVO> timeVOS = timeCollect.get(timeKey);


                //返回数据
                WaterQualityMergeVO waterQualityMergeVO = new WaterQualityMergeVO();
                waterQualityMergeVO.setAreaName(timeVOS.get(0).getAreaName());
                waterQualityMergeVO.setId(timeVOS.get(0).getId());//站点id
                waterQualityMergeVO.setSiteName(siteNameKey);   //站点名称
                waterQualityMergeVO.setJzmZ(timeVOS.get(0).getJzm());   //站点目标
                waterQualityMergeVO.setX(timeVOS.get(0).getX());
                waterQualityMergeVO.setY(timeVOS.get(0).getY());
                waterQualityMergeVO.setDataTime(timeVOS.get(0).getDataTime());

                String nowJzmFlag = null;//现状标记
                Integer codeFlag = 0;//现状编码标记
                StringBuilder overproof = new StringBuilder();//超标因子

                //根据类别分组
                Map<String, List<WaterQualityMergeDetailsVO>> paramNameCollect = timeVOS.stream().collect(Collectors.groupingBy(WaterQualityMergeDetailsVO::getParamName));
                for (String paramNameKey : paramNameCollect.keySet()) {
                    List<WaterQualityMergeDetailsVO> paramNameVOS = paramNameCollect.get(paramNameKey);

                    //计算数值
                    BigDecimal sum = new BigDecimal(0);
                    int i = 0;
                    for (WaterQualityMergeDetailsVO vo : paramNameVOS) {
                        sum = sum.add(new BigDecimal(vo.getDataValue()));
                        i++;
                    }
                    //防止分母为0异常
                    if (i == 0) {
                        i = 1;
                    }
                    //平均值
                    String dataValueString = sum.divide(new BigDecimal(i), 3, BigDecimal.ROUND_HALF_UP).toString();
                    switch (paramNameKey){
                        case "氨氮":
                            waterQualityMergeVO.setAdValue(dataValueString);
                            break;
                        case "总磷":
                            waterQualityMergeVO.setZlValue(dataValueString);
                            break;
                        case "高锰酸盐指数":
                            waterQualityMergeVO.setGmsyValue(dataValueString);
                            break;
                    }
                    //判断单个数据是否超标
                    SiteMonitorDataGetAllDto value = Constant.WaterStandard.getValue(paramNameKey, paramNameVOS.get(0).getJzm(), dataValueString);
                    Integer code = value.getCode();//类别现状编码
                    //判断站点现状(最高类别现状)
                    if (code > codeFlag) {
                        codeFlag = code;
                        nowJzmFlag = value.getNowJzm();//类别现状
                    }
                    //判断站点是否超标(全部类别达标则达标，否则超标)
                    Boolean ifOverproof = value.getIfOverproof();
                    if (ifOverproof) {
                        waterQualityMergeVO.setIfOverproofA(true); //站点是否超标
                        overproof.append(paramNameKey).append("(").append(dataValueString).append("),");
                    }
                }

                waterQualityMergeVO.setNowJzmZ(nowJzmFlag);//站点现状
                //加入超标因子和数值
                if (overproof.length() > 1) {
                    overproof.deleteCharAt(overproof.length() - 1);
                }

                if (waterQualityMergeVO.getIfOverproofA() == null) {
                    waterQualityMergeVO.setIfOverproofA(false);
                }
                waterQualityMergeVO.setOverproof(overproof.toString());

                list.add(waterQualityMergeVO);
            }
        }
        return list;
    }

    @Override
    public ReportAVo report(WordReportDto dto) {
        int state = dto.getState();
        ReportAVo reportAVo = new ReportAVo();
        if (state == 0 || state == 1) {
            //当月
            List<WaterQualityMergeDetailsVO> vos1 = this.disposeData3(baseMapper.report(dto.getAreaName(), dto.getBeginDate(), dto.getEndDate()));
            Integer A1 = 0;
            Integer A2 = 0;
            for (WaterQualityMergeDetailsVO vo : vos1) {
                if (vo.getCode() <= 3) {
                    A1++;
                }
                if (!vo.getIfOverproof()) {
                    A2++;
                }
            }
            reportAVo.setZA1(vos1.size() + "");
            reportAVo.setA1(A1.toString());
            BigDecimal divide = new BigDecimal(A2).divide(new BigDecimal(vos1.size()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            reportAVo.setA2(divide.toString());
            if (state == 0) {
                //上月
                List<WaterQualityMergeDetailsVO> vos2 = this.disposeData3(baseMapper.report(dto.getAreaName(), dto.getLastBeginDate(), dto.getLastEndDate()));
                Integer lastA1 = 0;
                Integer A3 = 0;
                for (WaterQualityMergeDetailsVO vo : vos2) {
                    if (vo.getCode() <= 3) {
                        lastA1++;
                    }
                    if (!vo.getIfOverproof()) {
                        A3++;
                    }
                }
                reportAVo.setZA2(vos2.size() + "");
                reportAVo.setLastA1(lastA1.toString());
                BigDecimal divide2 = new BigDecimal(A3).divide(new BigDecimal(vos2.size()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                reportAVo.setLastA2(divide2.toString());
                int i = divide.compareTo(divide2);
                if (i > 0) {
                    BigDecimal subtract = divide.subtract(divide2);
                    reportAVo.setA3("上升" + subtract + "个百分点");
                } else if (i < 0) {
                    BigDecimal subtract = divide2.subtract(divide);
                    reportAVo.setA3("下降" + subtract + "个百分点");
                } else {
                    reportAVo.setA3("无变化");
                }
            } else {
                //去年同月
                List<WaterQualityMergeDetailsVO> vos3 = this.disposeData3(baseMapper.report(dto.getAreaName(), dto.getLastYearBeginDate(), dto.getLastYearEndDate()));
                Integer A4 = 0;
                for (WaterQualityMergeDetailsVO vo : vos3) {
                    if (!vo.getIfOverproof()) {
                        A4++;
                    }
                }
                BigDecimal divide3 = new BigDecimal(A4).divide(new BigDecimal(vos3.size()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                int i2 = divide.compareTo(divide3);
                if (i2 > 0) {
                    BigDecimal subtract = divide.subtract(divide3);
                    reportAVo.setA4("上升" + subtract + "个百分点");
                } else if (i2 < 0) {
                    BigDecimal subtract = divide3.subtract(divide);
                    reportAVo.setA4("下降" + subtract + "个百分点");
                } else {
                    reportAVo.setA4("无变化");
                }
            }
        } else {
            //年度
            List<WaterQualityMergeDetailsVO> vos4 = this.disposeData3(baseMapper.report(dto.getAreaName(), dto.getYearBeginDate(), dto.getYearEndDate()));
            Integer A5 = 0;
            Integer A6 = 0;
            for (WaterQualityMergeDetailsVO vo : vos4) {
                if (vo.getCode() <= 3) {
                    A5++;
                }
                if (!vo.getIfOverproof()) {
                    A6++;
                }
            }
            reportAVo.setA5(A5.toString());
            BigDecimal divide4 = new BigDecimal(A6).divide(new BigDecimal(vos4.size()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            reportAVo.setA6(divide4.toString());
        }

//        reportAVo.setA7();
//        reportAVo.setA8();

        return reportAVo;
    }

    private List<StatementVo> disposeData(SimpleDateFormat sdf,List<StatementVo> list) throws ParseException {
        List<StatementVo> statementVos = new ArrayList<>();
        List<StatementVo> statementVosFlag = new ArrayList<>();
        String dataFlag = null;
        for (StatementVo vo : list){
            String dataTime = vo.getDataTime();
            String format = sdf.format(sdf.parse(dataTime));
            //判断是否第一次
            if (dataFlag == null){
                dataFlag = format;
            }
            //判断是否同一天
            if (format.equals(dataFlag)){
                statementVosFlag.add(vo);
            }else {
                dataFlag = format;
                //进一步处理
                StatementVo vo2 = this.disposeData2(statementVosFlag);
                statementVos.add(vo2);
                //重置
                statementVosFlag = new ArrayList<>();
                statementVosFlag.add(vo);
            }
        }
        //最后一条数据
        StatementVo vo3 = this.disposeData2(statementVosFlag);
        statementVos.add(vo3);
        return statementVos;
    }

    private StatementVo disposeData2(List<StatementVo> statementVosFlag) {
        if (statementVosFlag.isEmpty()) {
            return null;
        }
        String dataTimeFlag = statementVosFlag.get(0).getDataTime();
        String siteNameFlag = statementVosFlag.get(0).getSiteName();
        BigDecimal adValueFlag = BigDecimal.ZERO;
        BigDecimal zlValueFlag = BigDecimal.ZERO;
        BigDecimal gmsyValueFlag = BigDecimal.ZERO;
        for (StatementVo vo1 : statementVosFlag) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                if (!Objects.equals(siteNameFlag, vo1.getSiteName())
//                        || !Objects.equals(sdf.format(sdf.parse(dataTimeFlag)), sdf.format(sdf.parse(vo1.getDataTime())))) {
//                    throw new IllegalArgumentException("数据异常-->{},{}");
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
            BigDecimal adValue = vo1.getAdValue().equals("--") ? BigDecimal.ZERO : new BigDecimal(vo1.getAdValue());
            BigDecimal zlValue = vo1.getZlValue().equals("--") ? BigDecimal.ZERO : new BigDecimal(vo1.getZlValue());
            BigDecimal gmsyValue = vo1.getGmsyValue().equals("--") ? BigDecimal.ZERO : new BigDecimal(vo1.getGmsyValue());
            adValueFlag = adValueFlag.add(adValue);
            zlValueFlag = zlValueFlag.add(zlValue);
            gmsyValueFlag = gmsyValueFlag.add(gmsyValue);
        }
        int count = statementVosFlag.size();
        StatementVo vo2 = new StatementVo();
        vo2.setDataTime(dataTimeFlag);
        vo2.setSiteName(siteNameFlag);
        vo2.setAdValue(adValueFlag.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP).toString());
        vo2.setZlValue(zlValueFlag.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP).toString());
        vo2.setGmsyValue(gmsyValueFlag.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP).toString());
        return vo2;
    }


    private List<WaterQualityMergeDetailsVO> disposeData3(List<WaterQualityMergeDetailsVO> vos) {
        List<WaterQualityMergeDetailsVO> list = new ArrayList<>();
        //根据站点名称分组
        Map<String, List<WaterQualityMergeDetailsVO>> siteNameCollect = vos.stream().collect(Collectors.groupingBy(WaterQualityMergeDetailsVO::getSiteName));
        for (String siteNameKey : siteNameCollect.keySet()) {
            WaterQualityMergeDetailsVO vo = new WaterQualityMergeDetailsVO();
            vo.setSiteName(siteNameKey);
            List<WaterQualityMergeDetailsVO> voList = siteNameCollect.get(siteNameKey);
            String jzm = voList.get(0).getJzm();

            String nowJzmFlag = null;//现状标记
            Integer codeFlag = 0;//现状编码标记
            StringBuilder overproof = new StringBuilder();//超标因子
            for (WaterQualityMergeDetailsVO vo1 : voList) {
                //数据是否超标
                SiteMonitorDataGetAllDto value2 = Constant.WaterStandard.getValue(vo1.getParamName(), jzm, vo1.getDataValue());
                Integer code = value2.getCode();//类别现状编码
                //判断站点现状(最高类别现状)
                if (code > codeFlag) {
                    codeFlag = code;
                    nowJzmFlag = value2.getNowJzm();//类别现状
                }
                //判断站点是否超标(全部类别达标则达标，否则超标)
                Boolean ifOverproof = value2.getIfOverproof();
                if (ifOverproof) {
                    vo.setIfOverproof(true); //站点是否超标
                    overproof.append(vo1.getParamName()).append("(").append(vo1.getDataValue()).append("),");
                }
            }
            vo.setCode(codeFlag);
            vo.setNowJzm(nowJzmFlag);//站点现状
            //加入超标因子和数值
            if (overproof.length() > 1) {
                overproof.deleteCharAt(overproof.length() - 1);
            }
            if (vo.getIfOverproof() == null) {
                vo.setIfOverproof(false);
            }
            list.add(vo);
        }
        return list;
    }

}
